package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-master/cache"
	"order-master/moderls"
	"order-master/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user moderls.User

	err := moderls.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在或密码错误",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})

	return

}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := moderls.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	moderls.DB.Debug().Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var role []moderls.Role
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	moderls.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Debug().
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return

}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/

	var node []moderls.Node
	moderls.DB.Table("nodes").
		Joins(" LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where(" role_nodes.rid = ?", rid).Debug().Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}

func RepoAdd(c *gin.Context) {
	repo_code := c.PostForm("repo_code")
	repo_name := c.PostForm("repo_name")
	data := moderls.Repo{
		RepoCode: repo_code,
		RepoName: repo_name,
	}

	moderls.DB.Debug().Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	rep_id, _ := strconv.Atoi(c.PostForm("rep_id"))

	data := moderls.RepoOrder{
		OrderCode:  order_code,
		OrderNum:   order_num,
		OrderPrice: order_price,
		RepId:      rep_id,
	}

	moderls.DB.Debug().Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	/*
		SELECT
		  repo_orders.id AS OrderId,
		  repos.repo_code AS RepoCode,
		  repos.repo_name AS RepoName,
		  repo_orders.order_code AS OrderCode,
		  repo_orders.order_num AS OrderNum,
		  repo_orders.order_price AS OrderPrice
		FROM
		  repo_orders
		  LEFT JOIN repos ON repos.id = repo_orders.rep_id
	*/

	var order []moderls.RepoOrderList

	redis_key := "order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Table("repo_orders").
			Joins(" LEFT JOIN repos ON repos.id = repo_orders.rep_id").
			Select(
				"repo_orders.id AS OrderId",
				"repos.repo_code AS RepoCode",
				"repos.repo_name AS RepoName",
				"repo_orders.order_code AS OrderCode",
				"repo_orders.order_num AS OrderNum",
				"repo_orders.order_price AS OrderPrice",
			).Offset(offset).Limit(size).Debug().Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	var total int64

	moderls.DB.Model(&moderls.RepoOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  order,
		"total": total,
	})
	return

}

func OrderDetail(c *gin.Context) {

	id := c.Query("id")

	var order moderls.RepoOrderList

	redis_key := "order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Table("repo_orders").
			Joins(" LEFT JOIN repos ON repos.id = repo_orders.rep_id").
			Select(
				"repo_orders.id AS OrderId",
				"repos.repo_code AS RepoCode",
				"repos.repo_name AS RepoName",
				"repo_orders.order_code AS OrderCode",
				"repo_orders.order_num AS OrderNum",
				"repo_orders.order_price AS OrderPrice",
			).Where("repo_orders.id=?", id).Debug().Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return

}
